package com.gegong.imr.client.vbox.cmd;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.virtualbox_5_2.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class VmManageCmd extends AbstractVBoxCmd {

    private VmManageOption option;
    private IMachine machine;

    public VmManageCmd(@NonNull VirtualBoxManager virtualBoxManager, @NonNull String targetVm) {
        super(virtualBoxManager, targetVm);
    }

    @Override
    public Progress execute(Object... params) {
        option = (VmManageOption) params[0];
        super.execute(params);

        try {
            machine = getVirtualBox().findMachine(getTargetVm());
            switch (option) {
                case DELETE:
                    IProgress progress = deleteVm();
                    break;
            }

        } catch (Exception e) {
            progress.resultCode = Progress.RESULT_FAILURED;
            progress.errorInfo = e;
        } finally {
            progress.completed = true;
        }
        return progress;
    }


    private IProgress deleteVm() {
        List<IMedium> medias = machine.unregister(CleanupMode.DetachAllReturnHardDisksOnly);
        log.info("移除以下媒体-" + String.join(",", medias.stream().map(IMedium::getName).collect(Collectors.toList())));
        IProgress progress = machine.deleteConfig(medias);
        progress.waitForCompletion(TimeOuts.NONE);
        return progress;
    }

    @Override
    public String getName() {
        return option + "虚拟机" + getTargetVm();
    }
}
